<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\ShowHistoryByOwner;
use App\Admin\Repositories\Owner;
use App\Events\ContractGenerationEvent;
use App\Models\Building;
use App\Models\Fund;
use App\Models\House;
use App\Models\HouseFeeConfig;
use App\Models\Room;
use Carbon\Carbon;
use Dcat\Admin\Admin;
use Dcat\Admin\Controllers\AdminController;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Dcat\Admin\Widgets\Alert;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class OwnerController extends AdminController
{
    protected function grid()
    {
        return Grid::make(
            new Owner(['user', 'ownerable']),
            function (Grid $grid) {
                $grid->disableDeleteButton();
                $grid->disableBatchDelete();
                $grid->id->sortable();
                $grid->column('user.name', '承租人');
                $grid->column('user.mobile', '承租人电话');
                $grid->column('ownerable', '关联房产')->display(
                    function ($value) {
                        if (isset($value['building_id'])) {  // 房间详细名称显示
                            $building = Building::query()->with('house')->find($value['building_id']);

                            return $building->house->name." - ".$building->name." - ".$value['name'];
                        }
                        if (isset($value['house_id'])) {
                            $house = House::query()->find($value['house_id']);

                            return $house->name." - ".$value['name'];
                        }

                        return $value['name'];
                    }
                );
                $grid->column('cycle_price', '每期租金（不含水电等费用）')->display(
                    function ($value) {
                        return $value.'/'.\App\Models\Owner::$cycleUnitMap[$this->cycle_unit];
                    }
                );
                $grid->closed('合同状态')->display(
                    function ($value) {
                        return $value ? '关闭' : '开启';
                    }
                );
                $grid->started_at;
                $grid->ended_at;

                $grid->disableEditButton();
                $grid->filter(
                    function (Grid\Filter $filter) {
                        $filter->equal('id');
                    }
                );

                $grid->actions(
                    function ($actions) {
                        $actions->append(new ShowHistoryByOwner());
                    }
                );
            }
        );
    }

    // 测试
    public function test()
    {

    }

    /**
     * show界面
     * @param $id
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make(
            $id,
            new Owner('user'),
            function (Show $show) {
                $show->id;
                $show->name()->as(
                    function () {
                        return $this->user['name'];
                    }
                );
                $show->image->image('', 75);
                $show->email->as(
                    function () {
                        return $this->user['email'];
                    }
                );
                $show->mobile->as(
                    function () {
                        return $this->user['mobile'];
                    }
                );
                $show->gender->as(
                    function () {
                        return \App\Models\User::$genderMap[intval($this->user['gender'])];
                    }
                );
                $show->address->as(
                    function () {

                        if (!$this->address) {
                            return "未填写";
                        }
                        return $this->address['province'].$this->address['city'].$this->address['area'].$this->address['address'];
                    }
                );
                $show->contract->unescape()->as(
                    function ($images) {
                        $str = "";
                        foreach ($images as $image) {
                            $image = "storage/".$image;
                            $str .= "<img data-action='preview-img' src='{$image}' style='max-width:150px;max-height:400px' class='img'> &nbsp;&nbsp;";
                        }

                        return $str;
                    }
                );
                $show->create_admin_id('创建的管理员')->as(
                    function ($id) {
                        return DB::table('admin_users')->find($id)->username;
                    }
                );
                $show->cycle_price->as(
                    function ($value) {
                        if ($this->cycle == 1) {
                            return $value."/".\App\Models\Owner::$cycleUnitMap[$this->cycle_unit];
                        } else {
                            return $value."/".$this->cycle.'个'.\App\Models\Owner::$cycleUnitMap[$this->cycle_unit];
                        }
                    }
                );
                $show->deposit;
                $show->ownerable_id('关联房产')->as(
                    function ($value) {
                        $model = (new $this->ownerable_type)->find($value);
                        switch ($this->ownerable_type) {
                            case Room::class:
                                $model = $model->load('building.house');

                                return $model->building->house->name.' - '.$model->building->name.' - '.$model->name;
                                break;
                            case Building::class:
                                $model = $model->load('house');

                                return $model->house->name.' - '.$model->name;
                                break;
                            case House::class:
                                return $model->name;
                                break;
                            default:
                        }
                    }
                );

                $show->disableEditButton();
                $show->disableDeleteButton();

                $show->update_admin_id('更新的管理员')->as(
                    function ($id) {
                        return DB::table('admin_users')->find($id)->username;
                    }
                );
                $show->created_at;
                $show->updated_at;
            }
        );
    }

    /**
     * 继承父类的创建方法，目的是为from函数传递一个building_id
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        if ($category_id = request()->input('room_id')) {
            $category = Room::class;
        } elseif ($category_id = request()->input('building_id')) {
            $category = Building::class;
        } else {
            $category_id = 0;
            $category = Room::class;
        }

        return $content
            ->title($this->title())
            ->description('签订')
            ->body($this->form($category_id, $category));
    }

    /**
     * 继承父类的编辑方法，目的是为from函数传递一个building_id
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        if ($category_id = request()->input('room_id')) {
            $category = Room::class;
        } elseif ($category_id = request()->input('building_id')) {
            $category = Building::class;
        } else {
            $category_id = 0;
            $category = Room::class;
        }

        return $content
            ->title($this->title())
            ->description($this->description()['edit'] ?? trans('admin.edit'))
            ->body($this->form($category_id, $category)->edit($id));
    }

    /**
     * 表单
     * @param int $category_id
     * @param string $category
     * @return Form
     */
    protected function form($category_id = 0, $category = Room::class)
    {
        return Form::make(
            new Owner(['user']),
            function (Form $form) use ($category_id, $category) {
                $form->disableDeleteButton();
                $form->text('user.name', '承租人姓名')->required();
                $form->email('user.email', '邮件');
                $form->mobile('user.mobile', '电话')->required();
                $form->password('user.password', '密码')->required()->default('123456')->help('默认密码为：123456');
                $form->radio('user.gender', '性别')->options([0 => '男', 1 => '女'])->default(0)->required();
                $form->radio('user.status', '状态')->options([0 => '关闭', 1 => '开启'])->default(1)->required();
                $form->image('image')->required();
                $form->embeds(
                    'address',
                    function ($form) {
                        $form->text('province', '省');
                        $form->text('city', '市');
                        $form->text('area', '区');
                        $form->text('address', '详细地址');
                    }
                );
                $form->hidden('user.create_admin_id')->value(Auth::guard('admin')->id());
                $form->hidden('user.update_admin_id')->value(Auth::guard('admin')->id());
                $form->hidden('create_admin_id')->value(Auth::guard('admin')->id());
                $form->hidden('update_admin_id')->value(Auth::guard('admin')->id());
                $form->select('cycle')->options(range(1, 30))->default(0)->required();
                $form->select('cycle_unit')->options([0 => '月', 1 => '日', 2 => '年'])->default(0)->required();
                $form->decimal('cycle_price')->required();
                $form->decimal('deposit')->required();
                $form->decimal('inc')->default(0)->help("如果不设置该值，本合同为普通合同。如果设置该值，该合同将变为递增合同（即每个月租金按照该值递增）");
                $form->date('started_at')->required()->rules('required');
                $form->date('ended_at')->required()->rules('required');
                $form->textarea('description')->required();
                $form->multipleImage('contract')->required();
                $form->table(
                    'config',
                    function (Form\NestedForm $form) {
                        $config = HouseFeeConfig::query()->whereIn(
                            'type',
                            [HouseFeeConfig::TYPE_CYCLE, HouseFeeConfig::TYPE_METER_READING]
                        )->get();
                        $names = $config->map(
                            function ($value) {
                                $value->name = $value->name."(每/{$value->unit})";

                                return $value;
                            }
                        )->pluck('name', 'id');
                        $form->select('house_config_id', '配置项id')->options($names);
                        $form->decimal('price', '金额')->required();
                    }
                )->useTable()->required();
                $info = '<i class="fa fa-exclamation-circle"></i> 没有你需要的公共收付费项? <a style="color: red" href="'.route(
                        'admin.house-fee-config.create'
                    ).'">点我去添加配置</a>';
                $form->html(Alert::make($info)->info());
                if ($category_id) {
                    $form->hidden("ownerable_id", "id")->value($category_id);
                    $form->hidden("ownerable_type", "类型")->value($category);
                } else {
                    $form->hidden('ownerable_id');
                    $form->hidden('ownerable_type');
                    $info = '<i class="fa fa-exclamation-circle"></i> 概念理解: <br> 1. 整个房产, 比如: 整个博华A, B, C栋楼可以理解为一个房产 <br> 2.
某栋楼, 比如: A栋楼可以一栋楼<br>3. 某个房间, 比如: B栋楼三楼划分为2个房间(a房间, b房间), a房间可以理解为一个房间';
                    $form->html(Alert::make($info)->info());
                    $this->handleHouse($form);   // 显示租借房间表单
                }

                // 保存时
                $form->saving(
                    function (Form $form) {

                        // 合同时间校验
                        if (Carbon::parse($form->ended_at)->lte(Carbon::parse($form->started_at))) {
                            return $form->error('合同结束时间不得小于等于合同开始时间');
                        }
                        $temp = [];

                        // 处理公共项数据
                        if ($form->config) {
                            foreach ($form->config as $key => $value) {

                                if (empty($value['house_config_id']) || in_array($value['house_config_id'], $temp)) {
                                    $form->input("config.{$key}._remove_", 1);
                                }

                                $temp[] = $value['house_config_id'];
                            }
                        }

                        // 合同(租客)关联房产
                        $rent_type = intval($form->rent_type);
                        if ($rent_type === 1) { // 租借某个房间
                            $form->input('ownerable_id', $form->room);
                            $form->input('ownerable_type', Room::class);
                        } elseif ($rent_type === 2) { // 租借某栋楼
                            $form->input('ownerable_id', $form->building);
                            $form->input('ownerable_type', Building::class);
                        } elseif ($rent_type == 3) { // 租借某个房产
                            $form->input('ownerable_id', $form->house);
                            $form->input('ownerable_type', House::class);
                        }

                        // 校验出租情况
                        $arr = $this->validateHouse($form->input('ownerable_type'), $form->input('ownerable_id'));
                        if (!$arr['status']) {
                            return $form->error($arr['msg']);
                        }

                        $form->cycle = $form->cycle + 1;

                        $form->deleteInput(
                            [
                                'rent_type',
                                'house',
                                'room',
                                'building',
                            ]
                        );
                    }
                );

                $form->saved(
                    function (Form $form) {
                        // 回调
                        $ownerObj = \App\Models\Owner::query()->find($form->getKey());

                        // 押金进入账单
                        Fund::storeByModel(Fund::TYPE_DEPOSIT_INCOME, $ownerObj->deposit, $ownerObj, $ownerObj->user_id);

                        // 调用生成合同生成事件
                        event(new ContractGenerationEvent($ownerObj));
                    }
                );
            }
        );
    }

    /**
     * 校验某个房间，楼栋，房产是否可以出租
     * @param $ownerable_type
     * @param $ownerable_id
     * @return array
     */
    private function validateHouse($ownerable_type, $ownerable_id)
    {
        switch ($ownerable_type) {
            case House::class:
                $house = House::query()->with('building.rooms')->find($ownerable_id);
                // 判断自己是否已经被出租
                if ($house->is_rent) {
                    return ['status' => false, 'msg' => '该房产已被出租'];
                }
                foreach ($house->building as $building) {
                    if ($building->is_rent) {
                        return ['status' => false, 'msg' => '该房产的'.$building->name.'已被出租'];
                    }
                    foreach ($building->rooms as $room) {
                        if ($room->is_rent) {
                            return ['status' => false, 'msg' => '该房产的'.$building->name.'-'.$room->name.'已被出租'];
                        }
                    }
                }

                return ['status' => true, 'msg' => ''];
                break;
            case Building::class:
                $building = Building::query()->with(['rooms', 'house'])->find($ownerable_id);
                // 判断自己是否已经被出租
                if ($building->house->is_rent) {
                    return ['status' => false, 'msg' => '该栋楼所属房产已被出租'];
                }
                if ($building->is_rent) {
                    return ['status' => false, 'msg' => '该栋楼已被出租'];
                }
                foreach ($building->rooms as $room) {
                    if ($room->is_rent) {
                        return ['status' => false, 'msg' => '该栋楼的'.$room->name.'已被出租'];
                    }
                }

                return ['status' => true, 'msg' => ''];
                break;
            case Room::class:
                $room = Room::query()->with(['building.house'])->find($ownerable_id);
                // 判断自己是否已经被出租
                if ($room->is_rent) {
                    return ['status' => false, 'msg' => '该房间已被出租'];
                }
                if ($room->building->is_rent) {
                    return ['status' => false, 'msg' => '该房间所属楼栋已被出租'];
                }
                if ($room->building->house->is_rent) {
                    return ['status' => false, 'msg' => '该房间所属房产已被出租'];
                }

                return ['status' => true, 'msg' => ''];
                break;
            default :
                break;
        }
    }

    /**
     * 渲染选择租借房间的表单
     * @param Form $form
     */
    public function handleHouse(Form $form)
    {
//        $form->radio('rent_type', '租借房间')
//            ->options([1 => '租借某个房间', 2 => '租借某栋楼', 3 => '租借整个房产'])
//            ->default(1);
        $form->select('house', '房产')->options(
            House::query()->where('is_rent', false)->get()->pluck('name', 'id')
        )->load('building', '/api/building');
        $form->select('building', '楼栋')->load('room', '/api/room');
        $form->select('room', '房间')->rules(
            function ($form) {
                $room = Room::query()->with(['building', 'building.house'])->find(request()->room);
                if ($room && $room->is_rent && $room->building()->is_rent && $room->building()->house()->is_rent) {
                    $form->responseValidationMessages('room', '该房间已经出租');
                }
            }
        );

        Admin::script(
            <<<JS
var type = parseInt($("input[name='rent_type']:checked").val());
var house = $('input[name="house"]').parents('.form-group');
var building = $('input[name="building"]').parents('.form-group');
var room = $('input[name="room"]').parents('.form-group');

// if(type === 1) {
      house.show();    // 展示提交框
      building.show(); // 展示提交框
      room.show();
// } else if (type === 2){
//       house.show();    // 展示提交框
//       building.show(); // 展示提交框
//       room.hide();
// } else {
//       house.show();
//       building.hide();
//       room.hide();
// }

$('input[name="rent_type"]').on('click', function () {
    let type = parseInt($(this).val());
    // if(type === 1) {
      house.show();    // 展示提交框
      building.show(); // 展示提交框
      room.show();
    // } else if (type === 2){
    //   house.show();    // 展示提交框
    //   building.show(); // 展示提交框
    //   room.hide();
    // } else {
    //   house.show();
    //   building.hide();
    //   room.hide();
    // }
});
JS
        );
    }

    /**
     * 检查config是否包含水表，电表配置项
     * @param $temp
     */
    private function checkMeterConfig($temp)
    {
        $water_id = HouseFeeConfig::query()->where('name', '水')->first()->id;
        $electricity_id = HouseFeeConfig::query()->where('name', '电')->first()->id;

        $hasWater = false;
        $hasElectricity = false;
        foreach ($temp as $checkValue) {
            // 获取水表，电表在配置表中的id
            if ($water_id == $checkValue) {
                $hasWater = true;
            }
            if ($electricity_id == $checkValue) {
                $hasWater = true;
            }
        }

        if ($hasWater == false || $hasElectricity == false) {
            return false;
        }

        return true;
    }

}
